<!doctype html>
<html>
  <head>
    <title>PDF to Canvas</title>
  </head>
  <body>
    <input type="file" id="fileInput" />
    <div id="canvasContainer"></div>

    <!-- <script type="module" src="./pdf.min.js"></script> -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/pdf.js/2.8.335/pdf.min.js"></script>
    <!-- <script src="https://cdnjs.cloudflare.com/ajax/libs/pdf.js/2.8.335/pdf.worker.min.js"></script> -->
    <script>
      const input = document.getElementById('fileInput')
      const canvasContainer = document.getElementById('canvasContainer')

      input.addEventListener('change', (e) => {
        const file = e.target.files[0]
        console.log('file: ', file, file.name)

        const reader = new FileReader()

        reader.onload = (loadEvent) => {
          const pdfData = loadEvent.target.result

          // 使用PDFJS加载PDF文档
          pdfjsLib
            .getDocument({ data: pdfData })
            .promise.then((pdfDoc) => {
              pdfDoc.getPage(1).then((page) => {
                // 计算视口大小以适应Canvas
                const viewport = page.getViewport({ scale: 1.5 })
                const canvas = document.createElement('canvas')
                const context = canvas.getContext('2d')

                canvas.height = viewport.height
                canvas.width = viewport.width

                // 将Canvas添加到DOM中
                canvasContainer.appendChild(canvas)

                // 渲染页面
                const renderContext = {
                  canvasContext: context,
                  viewport: viewport
                }

                page.render(renderContext).promise.then(() => {
                  console.log('Page rendered')
                  const img = new Image()
                  img.src = canvas.toDataURL()
                  img.onload = () => {
                    canvasContainer.appendChild(img)
                  }
                })
              })
            })
            .catch((err) => {
              console.error('Error loading PDF: ', err)
            })
        }

        reader.readAsArrayBuffer(file)
      })
    </script>
  </body>
</html>
